
/**
 * StorageService - 通用存储服务
 * 
 * 提供简化的localStorage和sessionStorage操作接口
 * 支持JSON对象的自动序列化和反序列化
 * 
 * 用法示例:
 * 
 * // 注入服务
 * function MyController(StorageService) {
 *   // localStorage操作
 *   StorageService.local.set('key', {name: 'value'});
 *   var data = StorageService.local.get('key', defaultValue);
 *   StorageService.local.remove('key');
 *   StorageService.local.clear();
 * 
 *   // sessionStorage操作
 *   StorageService.session.set('tempKey', 'tempValue');
 *   var tempData = StorageService.session.get('tempKey');
 *   StorageService.session.remove('tempKey');
 *   StorageService.session.clear();
 * 
 *   // 批量操作
 *   StorageService.local.setMultiple({key1: 'value1', key2: 'value2'});
 *   var multiData = StorageService.local.getMultiple(['key1', 'key2']);
 * }
 */

const StorageService = function($localStorage, $sessionStorage) {
  'ngInject';

  const service = {};

  // localStorage 操作
  service.local = {
    // 设置值
    set: function(key, value) {
      $localStorage[key] = value;
    },

    // 获取值
    get: function(key, defaultValue) {
      return $localStorage[key] !== undefined ? $localStorage[key] : defaultValue;
    },

    // 删除值
    remove: function(key) {
      delete $localStorage[key];
    },

    // 清空所有数据
    clear: function() {
      Object.keys($localStorage).forEach(function(key) {
        delete $localStorage[key];
      });
    },

    // 检查键是否存在
    has: function(key) {
      return $localStorage[key] !== undefined;
    },

    // 获取所有键
    keys: function() {
      return Object.keys($localStorage);
    },

    // 批量设置
    setMultiple: function(dataObject) {
      Object.keys(dataObject).forEach(function(key) {
        $localStorage[key] = dataObject[key];
      });
    },

    // 批量获取
    getMultiple: function(keys) {
      const result = {};
      keys.forEach(function(key) {
        result[key] = $localStorage[key];
      });
      return result;
    },

    // 获取存储大小（估算）
    getSize: function() {
      let size = 0;
      for (let key in $localStorage) {
        if ($localStorage.hasOwnProperty(key)) {
          size += JSON.stringify($localStorage[key]).length;
        }
      }
      return size;
    }
  };

  // sessionStorage 操作
  service.session = {
    // 设置值
    set: function(key, value) {
      $sessionStorage[key] = value;
    },

    // 获取值
    get: function(key, defaultValue) {
      return $sessionStorage[key] !== undefined ? $sessionStorage[key] : defaultValue;
    },

    // 删除值
    remove: function(key) {
      delete $sessionStorage[key];
    },

    // 清空所有数据
    clear: function() {
      Object.keys($sessionStorage).forEach(function(key) {
        delete $sessionStorage[key];
      });
    },

    // 检查键是否存在
    has: function(key) {
      return $sessionStorage[key] !== undefined;
    },

    // 获取所有键
    keys: function() {
      return Object.keys($sessionStorage);
    },

    // 批量设置
    setMultiple: function(dataObject) {
      Object.keys(dataObject).forEach(function(key) {
        $sessionStorage[key] = dataObject[key];
      });
    },

    // 批量获取
    getMultiple: function(keys) {
      const result = {};
      keys.forEach(function(key) {
        result[key] = $sessionStorage[key];
      });
      return result;
    },

    // 获取存储大小（估算）
    getSize: function() {
      let size = 0;
      for (let key in $sessionStorage) {
        if ($sessionStorage.hasOwnProperty(key)) {
          size += JSON.stringify($sessionStorage[key]).length;
        }
      }
      return size;
    }
  };

  // 通用方法
  service.isSupported = function() {
    try {
      const testKey = '__ngStorage_test__';
      localStorage.setItem(testKey, 'test');
      localStorage.removeItem(testKey);
      return true;
    } catch (e) {
      return false;
    }
  };

  // 清空所有存储（localStorage 和 sessionStorage）
  service.clearAll = function() {
    service.local.clear();
    service.session.clear();
  };

  // 导出数据
  service.exportData = function() {
    return {
      localStorage: angular.copy($localStorage),
      sessionStorage: angular.copy($sessionStorage)
    };
  };

  // 导入数据
  service.importData = function(data) {
    if (data.localStorage) {
      service.local.setMultiple(data.localStorage);
    }
    if (data.sessionStorage) {
      service.session.setMultiple(data.sessionStorage);
    }
  };

  return service;
};

function initStorageService() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化存储服务模块');
    return;
  }

  angular.module('app.services.storage', ['ngStorage'])
    .service('StorageService', StorageService);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initStorageService();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initStorageService();
}